package oracle.springbootxm.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import oracle.springbootxm.pojo.GoodsInfo;
import oracle.springbootxm.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;


@RestController
public class PayController {


    private final String APP_ID = "2021000117644473";
    private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCFaVJoAEMmXpZYgmtnn6EbTOYNQ8Jh9GwyktEPeOj6oP6gVSpLAueTm5WLFL8jNX2APknXghumCRkoi/ZLDAVjEiwe+gFZrgkr/F9bQ3+psfrSlf3Sn+ci8iQILgaHxT3qoNXhrQwmEHimkBLsvXxI8/pWXDVtywTQI2sWTq2xIRjHe7NiYB/hFo+VtjceK2KVIU7UOomBcfe1FehvpNHmKdbK102r1hxzhpbdYw5QaPiiD54dxiTA524RUzU1cQthsfkWu24/mfGeKtARHE0qVdUhQRUay9oASm8wo8zptxvJB+/QY01jEn9Gqweh6xv0sB2SbrYAYkgfY8u34hFBAgMBAAECggEAeEJMajtyTHAPDpHhx3L5guZ6qZJe8nWl4qC9mzjeqq3dWSHsEdn4bfJdhxWYhmB9VNDRN1atHaot54Li7RtU7809wF6UQQbEdcX1HwtlVM5+zr0uJGLHs5SaLlVuxYxjF9ELe3bF8LoASASvSoA0PH7RNm/AKcxL9mM28NDTeUqS8lVr6RyKQxSYxTO10tDm7PDhmNV9Y8Qvf6CSuG6p3F7ERnf6gkFyNnVFc3uXAl3J5wTOhXhaBhUiy/Gst7WvhJoHaq+lt5Nf44CJLol425WWj/c/sorM8jTwAQBrQtDivxVglDp7/4Kun3J4T7GFeHYa6n9S43uRTA8zN/mXAQKBgQC/EzkzSulOwHuIVHtNjlSKVByDlXJ9u62bmWH+sv72tcfmicN0sZdYWfQQv/XJC3XBcpnKzrUHA6y1W2LVN/hrRL6pbf0h6D2hKfqHFGJ2siQivmFGt5tYdhvSKzUmDGz10EoNXQ1oWkOXV27ycEmJ/VIiNT0zkuh193hKK4iMGQKBgQCyvjC5Q6VBn8UUjyjxDm6cOD+uuVnu7IkVAa9KyIzRCSL2dEwXQ8q3K2BPD2ZBy0yjcpThbQYyvKk4LWZuZ9q8q0CrxE7OhR3YphuIqFWeFCa7kPlJvjKJSJVkXdlfqUnHDY8RZnphhAVtov8sbcnDAwRjHtE//jxIgutRiajTaQKBgQCp6gdYxIn6fRKdZjsL+cDWDfwZS0G367hzgQ9ytmwiqf4s1V9Zmz9x0vRGHN4NvUInF6kJf43dwffIgo69+vrPMR+3fVa321VKxxDBJHB3Cu01dET+5PGg1c7hs4ic4DnY0jO39IKixHoM0DSaJR5QNlPeladqAH71wG5YzqOrqQKBgQCUuFyP+XHJzWbMeWUmVMzBnKeX+E6U1igk21b/kShhUQnPJ+qbvOMxTpz+iyCZA8+Le23WtsDefE0MGfJNUIoWSyMvB9JOUUIJHgRwyycZtUiY7cINknw377WlYdTYnGFvhp+QacTP2Gov09wfGmYypRMEagLPDPkZmBy1piVbaQKBgAMT4KGye0Z6px7eegjC4Dm3akDe6NUlr8UhUMougEpZUBkEQv65Gop+FVP+1ttpOH8p1oDPdvffYYVM2kZgmYNyNBATWCgjgpH9PqwYZEhE9+KFhnCx8Hit6vp7q9KBCLGlmzPcXW1L8p6gPVkM08okgf1U1CrpmGBcWQIhdIV4";
    private final String CHARSET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhB2RyijptD/OvIUfN4MGemjegTX32yDGJO71HxkjU5d6isDji/N2IqEBgU2eHME+IXm75cV2MXi5CvnZ+wnJvBIUt1QsQL6VTgUAaT/nEIgVEuzHFl/LWMlGkbj4LcZn7LhiFKda9BJFL9KZHoFjBrst4WwftsyqWyPTDmr3aPJp+8o1ybnm2wvLooI5vampkq7HpZoiS9neriBLrr5FwQSYZ0sEZMuqrhSRHQSSiUa9NCo6soSkYrs7vNjV3r7RjAqTbcaGQ2agmmsWDPg7iD5+NhF0CZk73PiqPrer85ZXiAxyLinm1pX8AsT1QC4lnh2NrizXsqsWRqeYC7ngFQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://127.0.0.1/returnUrl";


    @RequestMapping("/aliapy")
    public void alipay(HttpServletResponse httpResponse, HttpSession session) throws IOException {

        SecureRandom r = new SecureRandom();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        GoodsInfo paygoods = (GoodsInfo)session.getAttribute("paygoods");
        paygoods.setGoodspic(out_trade_no);
        double total_amount = paygoods.getGoodsprice();
        System.out.println(total_amount);
        //订单名称，必填
        String subject = "突尼斯软籽石榴2.5-3斤装";
        //商品描述，可空
        String body = "酸甜多汁";
        request.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @ResponseBody
    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if (signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号=" + out_trade_no);
            System.out.println("支付宝交易号=" + trade_no);
            System.out.println("付款金额=" + total_amount);

            //支付成功，修复支付状态
//            Object payService = null;
//            payService.updateById(Integer.valueOf(out_trade_no));
            return "/paysuccess";//跳转付款成功页面
        } else {
            return "no";//跳转付款失败页面
        }

    }
}

